using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Drawing.Text;
using System.Globalization;
using Barbar.MapReport.Common;

namespace Barbar.MapReport.HtmlRender.Shapes {
  internal class CircleWithNumberShape : CircleShape {
    private int m_Number;

    public int Number {
      get { return m_Number; }
      set { m_Number = value; }
    }

    public CircleWithNumberShape() {
    }

    public CircleWithNumberShape(int radius, Color color, int number)
      : base(radius, color) {
      m_Number = number;
    }

    public override void Draw(System.Drawing.Graphics graphics) {
      base.Draw(graphics);
      graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
      float size = Math.Max(Width / 2.0f, 2.0f);
      Font font = null;
      SizeF labelSize = SizeF.Empty;
      while (size > 1.0f) {
        font = new Font(new FontFamily("Arial"), size , FontStyle.Bold);
        labelSize = graphics.MeasureString(Convert.ToString(m_Number, CultureInfo.InvariantCulture), font);
        if (Width < labelSize.Width)
          size *= 0.8f;
        else
          break;
      }

      graphics.DrawString(Convert.ToString(m_Number, CultureInfo.InvariantCulture), font, new SolidBrush(Color.Black), Width / 2 - labelSize.Width / 2, Width / 2 - labelSize.Height / 2 + 1);
    }

    #region IXmlSerializable Members

    public override void ReadXml(XmlReader reader) {
      reader.Read();
      if (reader.NodeType != XmlNodeType.Element || reader.Value == "cswn")
        throw new MapReportException("Excepted 'cswn'");
      Width = XmlConvert.ToInt32(reader.GetAttribute("w"));
      Height = XmlConvert.ToInt32(reader.GetAttribute("h"));
      Color = Color.FromArgb(XmlConvert.ToInt32(reader.GetAttribute("c")));
      Number = XmlConvert.ToInt32(reader.GetAttribute("n"));
    }

    public override void WriteXml(XmlWriter writer) {
      writer.WriteStartElement("cswn");
      writer.WriteAttributeString("w", XmlConvert.ToString(Width));
      writer.WriteAttributeString("h", XmlConvert.ToString(Height));
      writer.WriteAttributeString("c", XmlConvert.ToString(Color.ToArgb()));
      writer.WriteAttributeString("n", XmlConvert.ToString(Number));
      writer.WriteEndElement();
    }

    #endregion
  }
}
